# -*- coding: utf-8 -*-

import tkinter as tk
import serial
import serial.tools.list_ports
import keyboard
import webbrowser
global hotkey_set, input_text

def get_screen_size():
    return root.winfo_screenwidth(), root.winfo_screenheight()

def set_window_size(width_percent, height_percent):
    screen_width, screen_height = get_screen_size()
    size = tuple(int(x * screen_percent / 100) for x, screen_percent in zip((screen_width, screen_height), (width_percent, height_percent)))
    root.geometry('{}x{}'.format(*size))

# 定义一个函数来打开网站
def open_website():
    webbrowser.open("https://gitee.com/waterguy/Real-time-serial-port-status-viewing-assistant") 
def update_serial_ports():
    # 获取当前系统中的串口列表
    ports = serial.tools.list_ports.comports()
    connected_ports = [f"{port.device}: {port.description}" for port in ports]
    
    # 更新窗口中的串口状态
    ports_text = "\n".join(connected_ports) if connected_ports else "没有检测到已连接的串口。"
    status_label.config(text=ports_text)
    
    # 每隔100毫秒,更新一次
    root.after(100, update_serial_ports)

def toggle_window(event=None):
    # 如果窗口最小化了，则唤醒它
    if root.state() == 'iconic':
        root.deiconify()
        root.attributes('-topmost', True)  # 置顶窗口
    # 否则，最小化窗口
    elif root.state() == 'normal':
        root.iconify()

def set_hotkey():
    global entry, confirm_button, error_label, hotkey_frame, hotkey_set, set_hotkey_button
    if hotkey_set:
        if hotkey_set:
            keyboard.remove_hotkey(input_text)
            hotkey_set = False
           

    def on_confirm():
        check_first_set(True)
        input_text = entry.get()
        try:
            keyboard.add_hotkey(input_text, toggle_window)
            print(f"successfully set hotkey:'{input_text}'")
            hotkey_frame.pack_forget()
            hotkey_set = True
            
            set_hotkey_button.config(state=tk.NORMAL)  # 重新启用“设置快捷键”按钮
        except ValueError as e:
            error_label.config(text=str(e), fg='red')

    def on_cancel():
        hotkey_frame.pack_forget()
        set_hotkey_button.config(state=tk.NORMAL)  # 重新启用“设置快捷键”按钮
    # 禁用“设置快捷键”按钮
    set_hotkey_button.config(state=tk.DISABLED)

    # 创建一个 Frame 用于容纳快捷键设置界面
    hotkey_frame = tk.Frame(root)
    hotkey_frame.pack(pady=20)

    # 创建一个标签提示用户输入快捷键
    label = tk.Label(hotkey_frame, text="请输入快捷键（例如：ctrl+u）：")
    label.pack(pady=10)

    # 创建一个文本输入框
    entry = tk.Entry(hotkey_frame)
    entry.pack(pady=10)

    # 创建一个确认按钮
    confirm_button = tk.Button(hotkey_frame, text="确认", command=on_confirm)
    confirm_button.pack(side=tk.LEFT, padx=5, pady=10)

    # 创建一个取消按钮
    cancel_button = tk.Button(hotkey_frame, text="取消", command=on_cancel)
    cancel_button.pack(side=tk.RIGHT, padx=5, pady=10)

    # 创建一个错误标签，用于显示错误信息
    error_label = tk.Label(hotkey_frame, text="")
    error_label.pack(pady=10)

# 定义一个函数来检查First_set的状态
def check_first_set(event):
    if event == False:
        print("fuck")
        keyboard.add_hotkey("ctrl+left", toggle_window)
    elif event == True:
        print("shit")
        keyboard.remove_hotkey("ctrl+left")
# 创建主窗口
root = tk.Tk()
root.title("串口状态实时监控")
# 添加logo，确保logo文件存在并且是.ico格式

# root.iconbitmap('I:/Real-time-serial-port-status-viewing-assistant/waterguy.ico')

# 创建一个标签，用于显示串口状态
status_label = tk.Label(root, text="正在检查串口状态...", font=("Helvetica", 12), anchor='w', justify='left')
status_label.pack(pady=20)
# 自定义设置适应屏幕的窗口大小
set_window_size(25, 25)

# 创建一个按钮，点击时设置快捷键
set_hotkey_button = tk.Button(root, text="设置快捷键", command=set_hotkey)
set_hotkey_button.pack(side=tk.LEFT, padx=(20, 10))  # 左侧按钮，左边距20，右边距10

# 创建一个按钮，点击时打开网站
open_website_button = tk.Button(root, text="开源工程地址", command=open_website)
open_website_button.pack(side=tk.RIGHT, padx=(10, 20)) # 右侧按钮，左边距10，右边距20 
# 初始化 hotkey_set
hotkey_set = False

# 启动串口状态更新
update_serial_ports()

check_first_set(False)

# 启动主循环
root.mainloop()
